package com.ygqh.baby.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ygqh.baby.ao.ReturnType;
import com.ygqh.baby.mapper.YgReturnOrderMapper;
import com.ygqh.baby.model.YgReturnOrderDetailModel;
import com.ygqh.baby.model.YgReturnOrderInfoModel;
import com.ygqh.baby.model.YgReturnOrderModel;
import com.ygqh.baby.po.YgReturnOrderLog;
import com.ygqh.baby.service.YgReturnOrderLogService;
import com.ygqh.baby.service.YgReturnOrderService;

@Service
public class YgReturnOrderServiceImpl implements YgReturnOrderService {
	
	@Autowired
	private YgReturnOrderMapper ygReturnOrderMapper;
	@Autowired
	private YgReturnOrderLogService ygReturnOrderLogService;

	@Override
	public List<YgReturnOrderModel> findReturnList(Long userId, int limit) {
		return ygReturnOrderMapper.selectReturnList(userId, limit);
	}

	@Override
	public YgReturnOrderInfoModel findReturnOrderInfo(String returnCode, Long userId) {
		YgReturnOrderInfoModel orderInfo = ygReturnOrderMapper.selectReturnOrderInfo(returnCode, userId);
		setLastProgress(orderInfo);
		if (orderInfo.getReturnType().equals(ReturnType.Change)) {
			handlerDetail(orderInfo);
		}
		return orderInfo;
	}

	private void handlerDetail(YgReturnOrderInfoModel orderInfo) {
		List<YgReturnOrderDetailModel> sDetailList = new ArrayList<>();
		List<YgReturnOrderDetailModel> detailList = new ArrayList<>();
		
		List<YgReturnOrderDetailModel> sourceDetailList = orderInfo.getSourceDetailList();
		
		Map<Long, List<YgReturnOrderDetailModel>> sourceDetailMap = sourceDetailList.parallelStream()
				.collect(Collectors.groupingBy(YgReturnOrderDetailModel::getSourceSkuId));
		sourceDetailMap.forEach((sourceSkuId, detailModels) -> {
			Long amount = detailModels.parallelStream().map(o -> o.getAmount()).reduce((a1, a2) -> (a1 + a2)).get();
			YgReturnOrderDetailModel model = detailModels.get(0);
			model.setAmount(amount);
			sDetailList.add(model);
		});
		
		Map<Long, List<YgReturnOrderDetailModel>> subDetailMap = sourceDetailList.parallelStream()
				.collect(Collectors.groupingBy(YgReturnOrderDetailModel::getSkuId));
		subDetailMap.forEach((skuId, detailModels) -> {
			Long amount = detailModels.parallelStream().map(o -> o.getAmount()).reduce((a1, a2) -> (a1 + a2)).get();
			YgReturnOrderDetailModel model = detailModels.get(0);
			model.setAmount(amount);
			detailList.add(model);
		});

		orderInfo.setSourceDetailList(sDetailList);
		orderInfo.setDetailList(detailList);
	}

	private void setLastProgress(YgReturnOrderInfoModel orderInfo) {
		List<YgReturnOrderLog> scheduleList = ygReturnOrderLogService.findReturnScheduleList(orderInfo.getReturnCode());
		orderInfo.setLastProgress(scheduleList.get(0).getOperation());
		orderInfo.setLastProgressTime(scheduleList.get(0).getCreateTime());
	}

}
